/**
 * [mongoose description]
 * @type {[type]}
 */
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const ObjectId = Schema.ObjectId

const ArticleSchema = new Schema({
	author_id: {
		type: ObjectId,
		ref: 'User'
	},
	title: {
		type: String,
		unique: true
	},
	images:{
		type:Array
	},
	content: String,
	tags: [{
		type: ObjectId,
		ref: 'Tag'
	}],
	comment: [{
		type: ObjectId,
		ref: 'Comment'
	}],
	visit_count: {
		type: Number,
		default: 0
	},
	comment_count: {
		type: Number,
		default: 0
	},
	like_count: {
		type: Number,
		default: 0
	},
	status: {
		//0:草稿 1:发布
		type: Number,
		default: 0
	},
	create_time: {
		type: Date,
		default: Date.now()
	},
	publish_time: {
		type: Date,
		default: Date.now()
	},
	update_time: {
		type: Date,
		default: Date.now()
	}
})

ArticleSchema.pre('save', function(next) {
	if (this.isNew) {
		this.update_time = this.create_time = Date.now()
	} else {
		this.update_time = Date.now()
	}
	next()
})

ArticleSchema.pre('findOneAndUpdate', function(next) {
	this.findOneAndUpdate({}, {
		update_time: Date.now()
	})
	next()
})

ArticleSchema.virtual('info').get(function() {
	return {
		'_id': this._id,
		'title': this.title,
		'content': this.content,
		'images': this.images,
		'visit_count': this.visit_count,
		'comment_count': this.comment_count,
		'like_count': this.like_count,
		'publish_time': this.publish_time
	}
})

mongoose.model('Article', ArticleSchema)